<?php

namespace backend\controllers;

use Yii;
use backend\models\BuildType;
use backend\models\BuildTypeSearch;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\BulidCity;
use backend\models\BuildCity;
use yii\web\UploadedFile;
use backend\models\Image;
use yii\web\ForbiddenHttpException;
use backend\models\AdminInfo;
use common\models\City;
use backend\models\GrpSpace;
use backend\models\OperatorRelation;
use backend\models\GrpCity;

use backend\models\Taozhuang;
/**
 * BuildTypeController implements the CRUD actions for BuildType model.
 */
class BuildTypeController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }
    public function beforeAction($action)
    {
    	//如果未登录，则直接跳转
    	if(Yii::$app->user->isGuest){
    		return $this->redirect(['/site/login']);
    	}  
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	if(\Yii::$app->user->can('build-type')){
    		if($action == 'create' && AdminInfo::check_create('create') == true){
				return true;
			}
    	   	if($this->_access($action) == true){
    			return true;
    		}   		
    		$id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;
    		if($id != 0){
    			$model = $this->findModel($id);
    			if($action == 'view' && AdminInfo::check_hasoperator(Yii::$app->user->identity->id,$model['admin_id'],'view')){
    				return true;
    			}elseif ($action != 'view' && AdminInfo::check_hasoperator(Yii::$app->user->identity->id,$model['admin_id'],'edit')){
    				return true;
    			}else{
    				throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    			}
    		}
			return true;
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	}
    }
    //允许访问
    function _access($action){
    	$action_list = array(
    			'index',
    	);
    	if(in_array($action, $action_list)){
    		return true;
    	}
    }
    /**
     * Lists all BuildType models.
     * @return mixed
     */
    public function actionIndex()
    {
    
         
        $searchModel = new BuildTypeSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single BuildType model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new BuildType model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BuildType();
        $login_id = Yii::$app->user->identity->id;
		if(Yii::$app->user->identity->user_type == 1){//后台管理员
			  $bids = BuildCity::find()->all();
			$buileCity = BuildCity::find()->distinct()->select('bulid_city.city_id,grp_city.name')->leftJoin('grp_city','grp_city.id=bulid_city.city_id')->asArray()->all();
			$city_list= ArrayHelper::map($buileCity,'city_id','name');  
		}else{
			$address = City::admin_province($login_id);
			$city_arr = array();
			foreach ($address['city'] as $val){
				array_push($city_arr, $val['id']);
			}
			$city_ids = implode(',', $city_arr);
			$bids = BuildCity::find()->where("city_id in ({$city_ids})")->all();
            $buileCity = BuildCity::find()->select('bulid_city.city_id,grp_city.name')->leftJoin('grp_city','grp_city.id=bulid_city.city_id')->where("city_id in ({$city_ids})")->asArray()->all();
            $buileCity= ArrayHelper::map($buileCity,'city_id','name');
            //待修改
            $OperatorRelation=new OperatorRelation();
            $uid=Yii::$app->user->identity->user_id;
            $citylist_Str=$OperatorRelation->getCityIdById($uid);
            $cityList=explode(",", $citylist_Str);
            $city_list=array();
            for($i=0;$i<count($cityList);$i++){
                $sql="select  * from grp_city where id=:id";
                $param=array(":id"=>$cityList[$i]);
                $cityInfo=GrpCity::findBySql($sql,$param)->asArray()->One();
                $city=array("id"=>$cityInfo['id'],"name"=>$cityInfo['name']);
                $city_list[$city['id']]=$city['name'];
            }
		}
        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
        	$model->image_upload = UploadedFile::getInstance($model, 'image_upload');
        	if ($model->image_upload) {
        		$image_arr = Image::save_image_to_files($model, '414', $model->bid.'_'.$model->title, 'build_type_image_thumb', 'build_type_image_small');
        		var_dump($image_arr);
        		$model->img_url_id = $image_arr['img_url_id'];
        		$model->img_thumb_id = $image_arr['img_thumb_id'];
        		$model->img_small_id = $image_arr['img_small_id'];
        		$model->image_upload = '';
        		
        	}
			$model->admin_id = Yii::$app->user->identity->id;
        	$model->save();

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            	'bids' => $bids,
                'buileCity' => $city_list,
            ]);
        }
    }

    /**
     * Updates an existing BuildType model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $_arr = explode(',', $model->tz_img_list);
        foreach ($_arr as $value){        	
        }
        $login_id = Yii::$app->user->identity->id;
        	if(Yii::$app->user->identity->user_type == 1){//后台管理员
        		$bids = BuildCity::find()->all();
        	}else{
        		$bids = BuildCity::find()->where("admin_id={$login_id}")->all();
        	}            	
	        	if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
	        		$model->image_upload = UploadedFile::getInstance($model, 'image_upload');
	        		if ($model->image_upload) {
	        			$image_arr = Image::save_image_to_files($model, '414', $model->bid.'_'.$model->title, 'build_type_image_thumb', 'build_type_image_small',$model->img_url_id,$model->img_thumb_id,$model->img_small_id);
	        			$model->image_upload = '';
	        		}
	        	//重新格式化
	        		$have_arr_tz_img_list = explode(',', $model->tz_img_list);
	        		$all_space = GrpSpace::findAll(['useing'=>1]);
	        		$arr_tz_small_img = array();
	        		$count=count($have_arr_tz_img_list);
	        		for($i=0;$i<$count;$i++){
	        		    for($j=0;$j<count($all_space);$j++){
	        		        for($z=0;$z<$count;$z++){
	        		            if(!empty($have_arr_tz_img_list[$z])){
	        		                $space_id=Taozhuang::get_space_id($have_arr_tz_img_list[$z]);
	        		                if($space_id==$all_space[$j]['id']){
	        		                    array_push($arr_tz_small_img, $have_arr_tz_img_list[$z]);
	        		                    unset($have_arr_tz_img_list[$z]);
	        		                    break;
	        		                }
	        		            }
	        		        }
	        		    }
	        		}
	        	$model->tz_img_list = implode(',', $arr_tz_small_img);
	        	$model->save();
	
	            return $this->redirect(['view', 'id' => $model->id]);
	        } else {
	            return $this->render('update', [
	                'model' => $model,
	            	'bids' => $bids,
	            ]);
	        }

    }

    /**
     * Deletes an existing BuildType model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the BuildType model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return BuildType the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {

    	$model = BuildType::findOne($id);
        if ($model !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    public function actionDeleteBuildType($tz_id,$type_id,$tz_img_list)
    {
        //$tz_id 删除的id   type_id为当前buildtype的id  tz_img_list为当前buildtype的tz_img_list 
        $have_arr_tz_img_list = explode(',',$tz_img_list);
        $key = array_search($tz_id, $have_arr_tz_img_list);
    	if ($key !== false)array_splice($have_arr_tz_img_list, $key, 1);
    	$model = BuildType::findOne(['id'=>$type_id]);
    	//重新排序 按照分类来
    	$all_space = GrpSpace::findAll(['useing'=>1]);
    	$arr_tz_small_img = array();
    	$count=count($have_arr_tz_img_list);
    	for($i=0;$i<$count;$i++){
    	    for($j=0;$j<count($all_space);$j++){
    	        for($z=0;$z<$count;$z++){
    	            if(!empty($have_arr_tz_img_list[$z])){
    	                $space_id=Taozhuang::get_space_id($have_arr_tz_img_list[$z]);
    	                if($space_id==$all_space[$j]['id']){
    	                    array_push($arr_tz_small_img, $have_arr_tz_img_list[$z]);
    	                    unset($have_arr_tz_img_list[$z]);
    	                    break;
    	                }
    	            }
    	        }
    	        
    	    }
    	}
    	$model->tz_img_list = implode(',', $arr_tz_small_img);
    	if($model->save()){echo 'ok';}else{}
    }
}
